﻿using System;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace SearchLogs
{
    class Program
    {
        static void Main(string[] args)
        {
            // Show Help
            if(
                args.Count() != 2 ||
                (!args[0].ToLower().StartsWith("-logfolder:") && !args[1].ToLower().StartsWith("-searchstring:"))
              )
            {
                ShowHelp();
                Environment.Exit(0);

            }

            string Path = string.Empty;
            string SearchPattern = string.Empty;
            List<string> BadArgument = new List<string>();

            // find out parameters
            foreach (string arg in args)
            {
                if(arg.ToLower().StartsWith("-logfolder:")) { Path = arg.Substring(11); }
                else if(arg.ToLower().StartsWith("-searchstring:")) { SearchPattern = arg.Substring(14); }
                else { BadArgument.Add(arg);}
            }

            if (BadArgument.Count() > 0)
            {
                foreach (string arg in BadArgument) {
                    Console.WriteLine("Invalid argument: " + arg);
                }

                Environment.Exit(1);
            }

            // check the log files
            FindMatches(Path, SearchPattern);
        }

        static void ShowHelp()
        {
            Console.WriteLine("LOG SEARCHER v1.0.1.2");
            Console.WriteLine("Official distribution source:  https://searchlogs.codeplex.com/");
            Console.WriteLine("Syntax:     SearchLogs.exe -LogFolder:\"PathToLogs\" -SearchString:\"RegularExpression\"");
            Console.WriteLine("");
            Console.WriteLine("Parameters:");
            Console.WriteLine("   LogFolder          The explicit path where the log files are stored.");
            Console.WriteLine("   SearchString       The regular expression formatted pattern to match.");
        }

        static bool CanAccessFile(string File)
        {

            try {
                return System.IO.File.Exists(File);
            }

            catch
            {
                return false;
            }
        }

        static bool CanAccessFolder(string Folder)
        {

            try
            {
                return System.IO.Directory.Exists(Folder);
            }

            catch
            {
                return false;
            }
        }

        static void FindMatches(string Path, string SearchString)
        {
            if(CanAccessFolder(Path))
            {
                foreach (string entry in System.IO.Directory.GetFiles(Path))
                {
                    UInt32 LineNumber = 0;
                    if(CanAccessFile(entry))
                    {
                        using (StreamReader reader = new StreamReader(entry))
                        {

                            while (!reader.EndOfStream)
                            {
                                LineNumber++;
                                string Line = reader.ReadLine();
                                if (Regex.IsMatch(Line, SearchString))
                                {
                                    Console.WriteLine(string.Format("Match on line {0} in file \"{2}\" \n{1}", LineNumber, Line, entry));
                                    Console.WriteLine("===========================================");
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unable to access file: " + entry);
                    }
                }
            }
            else { Console.WriteLine("Unable to access directory " + Path); }
        }
    }
}
